import { insertCart, findCartList, deleteCart, updateCart, checkAllCart } from '@/api/good'
// 购物车状态
export default {
  namespaced: true,
  state: () => ({
    list: []
  }),
  getters: {
    // 总钱数
    allPrice (state) {
      return state.list.reduce((a, c) => a + c.count * c.price, 0)
    },
    // 总数量
    allCount (state) {
      return state.list.reduce((a, c) => a + c.count, 0)
    },
    // 已选择商品的数量
    seletedCount (state) {
      // 找到已选择的商品进行计算
      return state.list.filter(item => item.selected === true).reduce((a, c) => a + c.count, 0)
    },
    // 已选择商品的总价钱
    seletedPrice (state) {
      return state.list.filter(item => item.selected === true).reduce((a, c) => a + c.count * c.price, 0)
    },
    // 全选的回显
    isAllCheck (state) {
      // 得到每一项是否是选中的状态
      return state.list.every(item => item.selected === true)
    }
  },
  mutations: {
    // 保存购物车信息
    SET_CARTLIST (state, list) {
      state.list = list
    },
    // 设置选中状态
    SET_SELETED (state, { i, selected }) {
      const item = state.list.find(item => item.skuId === i.skuId) // 根据id得到当前项
      item.selected = selected
    }
  },
  actions: {
    // 添加购物车
    async addCartList (ctx, { skuId, count }) {
      await insertCart({ skuId, count })
      // 获取购物车列表
      const res = await findCartList()
      ctx.commit('SET_CARTLIST', res.result)
    },
    // 删除购物车
    async removeCart (ctx, ids) {
      await deleteCart(ids)
      // 获取购物车列表
      const res = await findCartList()
      ctx.commit('SET_CARTLIST', res.result)
    },
    // 单选
    async asyncSingleCheck (ctx, goods) {
      // 调用单选接口
      await updateCart(goods)
      const res = await findCartList()
      ctx.commit('SET_CARTLIST', res.result)
    },
    // 多选
    async asyncAllCheck (ctx, selected) {
      await checkAllCart({
        selected,
        ids: ctx.state.list.map(item => item.skuId) // 所有商品的id组成的数组
      })
      const res = await findCartList()
      ctx.commit('SET_CARTLIST', res.result)
    },
    // 数量修改
    async asyncChangeCount (ctx, { i, count }) {
      await updateCart({
        skuId: i.skuId,
        selected: i.selected,
        count
      }) // 和单选是同一个接口
      const res = await findCartList()
      ctx.commit('SET_CARTLIST', res.result)
    }
  }
}
